package cn.yywd_123.Light.mod;

/*
 *  Author: yywd_123
 *  Date: 2022/8/13
 */

import cn.yywd_123.Light.main.LightMain;
import cn.yywd_123.Light.main.utils.JarLoader;
import cn.yywd_123.LightAPI.IMod;
import cn.yywd_123.LightAPI.IModUtils;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

public class ModManager {
	private static final List<IMod> modList = new ArrayList<>();
	private static final List<UUID> modUUIDList = new ArrayList<>();

	public static final JarLoader jarLoader = new JarLoader(new URL[]{}, ClassLoader.getSystemClassLoader());

	public void loadMods() {
		try {
			File jarPath = new File("Light-mods/");
			if (!jarPath.exists()) {
				LightMain.logger.warn("未检测到模组目录,正在创建: " + jarPath.getAbsolutePath());
				jarPath.mkdir();
				return;
			}
			for (File jarFile : Objects.requireNonNull(jarPath.listFiles((dir, name) -> name.endsWith(".jar")))) {
				jarLoader.addJar(jarFile);
				//new JarFile(new File(Objects.requireNonNull(jarLoader.getResource("META-INF/MANIFEST.MF")).toURI())).getManifest().getAttributes("");
				//String jarFileName = jarFile.getName();
				//Class<?> clazz = jarLoader.loadClass(jarFileName.substring(0, jarFileName.length() - 3) + "ModMain");
				try (JarFile jar = new JarFile(jarFile)) {
					Class<?> clazz = jarLoader.loadClass(jar.getManifest().getMainAttributes().getValue("LightMod-Main-Class"));
					Object clazzInstance = clazz.newInstance();
					Method m = clazz.getDeclaredMethod("ModInit", IModUtils.class);
					m.invoke(clazzInstance, new ModUtils());
				} catch (Exception e) {
					LoggerFactory.getLogger(this.getClass()).error("模组" + jarFile.getName() + "加载失败");
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void addMod(UUID modUUID, IMod mod) {
		if (!modUUIDList.contains(modUUID)) {
			modList.add(mod);
			modUUIDList.add(modUUID);
			LoggerFactory.getLogger(this.getClass()).info("成功加载模组: [" + mod.getModName()[0] + "] 版本: [" + mod.getModVersion() + "] UUID: [" + modUUID.toString() + "]");
		}
	}

	public List<IMod> getMods() {
		return modList;
	}

	public List<IMod> getEnabledMods() {
		return modList.stream().filter(IMod::isEnable).collect(Collectors.toList());
	}


	public void close() {
		getEnabledMods().forEach(IMod::stop);
		modList.clear();
		modUUIDList.clear();
	}

	public void reload() {
		modList.clear();
		modUUIDList.clear();
	}

	public IMod getMod(String modName) {
		for (IMod mod : modList) {
			if ((modName.equalsIgnoreCase(mod.getModName()[0]))) return mod;
			else if (mod.getModName().length > 1) {
				for (String str : mod.getModName()) {
					if (modName.equalsIgnoreCase(str)) return mod;
				}
			}
		}
		return null;
	}

	public String[] getAvailableMods() {
		String[] mods = new String[modList.size()];
		int i = 0;
		for (IMod mod : modList) {
			mods[i] = mod.getModName()[0];
			i++;
		}
		return mods;
	}
}
